package ru.neoflex.jedit.plugin.core;

import javax.swing.event.CaretListener;
import javax.swing.event.CaretEvent;
import org.gjt.sp.util.Log;
import ru.neoflex.jedit.plugin.domain.autocomplete.XhtmlAutocompleteHelper;
import ru.neoflex.jedit.plugin.domain.autocomplete.XhtmlAutocompleteSettings;
import org.gjt.sp.jedit.jEdit;
import ru.neoflex.jedit.plugin.utils.XhtmlPosition;
import ru.neoflex.jedit.plugin.utils.XhtmlUtils;

/**
 * Обработчик именения положения каретки для WhisdomBar.
 */
public class XhtmlCaretListener implements CaretListener {
    public void caretUpdate(CaretEvent e) {
        XhtmlAutocompleteSettings settings = NeoflexState.getInstance().getXhtmlAutocompleteSettings();
        int position = e.getDot();
        String text = jEdit.getActiveView().getTextArea().getText();

        XhtmlPosition xp = XhtmlUtils.defineXhtmlPosition(text, position);
        if (xp == XhtmlPosition.IN_OPEN_TAG) {
            String hint = "IN_OPEN_TAG" + XhtmlAutocompleteHelper.generateHint(settings, text, position);
            NeoflexState.getInstance().getWhisdomBar().setText(hint);
        }
        if (xp == XhtmlPosition.EMPTY_SPACE) {
            NeoflexState.getInstance().getWhisdomBar().setText("EMPTY_SPACE");
        }
        if (xp == XhtmlPosition.IN_CLOSE_TAG) {
            NeoflexState.getInstance().getWhisdomBar().setText("IN_CLOSE_TAG");
        }
        if (xp == XhtmlPosition.IN_EL_EXPRESSION) {
            String elExpression = XhtmlUtils.extractElExpression(text, position);
            if (elExpression != null) {
                String hint = NeoflexState.getInstance().getHintForELExpression(elExpression);

                NeoflexState.getInstance().getWhisdomBar().setText(elExpression);
            } else {
                NeoflexState.getInstance().getWhisdomBar().setText("IN_EL_EXPRESSION");
            }
        }
        if (xp == XhtmlPosition.IN_ATTRIBUTE) {
            NeoflexState.getInstance().getWhisdomBar().setText("IN_ATTRIBUTE");
        }
    }
}
